package com.eden.manage.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.eden.manage.dto.PageComDto;
import com.eden.manage.dto.UserInfoDto;
import com.eden.manage.dto.agent.AgentInviteDto;
import com.eden.manage.mapper.EdenPlatAgentInfoMapper;
import com.eden.manage.mapper.EdenPlatAgentInviteMapper;
import com.eden.manage.mapper.EdenPlatMapper;
import com.eden.manage.model.EdenPlat;
import com.eden.manage.model.EdenPlatAgentInfo;
import com.eden.manage.model.EdenPlatAgentInvite;
import com.eden.manage.req.query.AgentInviteQuery;
import com.eden.manage.utils.InviteCodeGenerator;
import com.eden.manage.utils.WebUserUtils;
import eden.api.common.enums.UserTypeEnum;
import eden.api.common.utils.ErrorEnums;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AgentInviteService {

    private final EdenPlatAgentInviteMapper agentInviteMapper;

    private final EdenPlatAgentInfoMapper edenPlatAgentInfoMapper;

    private final EdenPlatMapper edenPlatMapper;

    public PageComDto<AgentInviteDto> pageList(AgentInviteQuery query){
        dealAuth(query);
        PageComDto<AgentInviteDto> pageDto = new PageComDto<>();
        int count = agentInviteMapper.countByPage(query);
        if(count > 0){
            List<AgentInviteDto> inviteDtos = agentInviteMapper.selectPageList(query);
            dealPlatAndAgentName(inviteDtos);
            pageDto.setList(inviteDtos);
        }
        pageDto.setCount(count);
        return pageDto;
    }

    private void dealPlatAndAgentName(List<AgentInviteDto> inviteDtos) {
        if(CollectionUtils.isEmpty(inviteDtos)){
            return;
        }
        List<Long> platIds = inviteDtos.stream().map(AgentInviteDto::getPlatId).distinct().collect(Collectors.toList());
        Map<Long, String> platNameMap = edenPlatMapper.selectListByIds(platIds).stream().collect(Collectors.toMap(EdenPlat::getId, EdenPlat::getPlatName, (it1, it2) -> it1));
        List<Long> agentIds = inviteDtos.stream().map(AgentInviteDto::getAgentId).distinct().collect(Collectors.toList());
        Map<Long, String> agentMap = edenPlatAgentInfoMapper.selectListByIds(agentIds).stream().collect(Collectors.toMap(EdenPlatAgentInfo::getId, EdenPlatAgentInfo::getAgentName, (it1, it2) -> it1));
        for (AgentInviteDto inviteDto : inviteDtos) {
            inviteDto.setPlatName(platNameMap.get(inviteDto.getPlatId()));
            inviteDto.setAgentName(agentMap.get(inviteDto.getAgentId()));
        }
    }

    private void dealAuth(AgentInviteQuery pageQuery) {
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        if(UserTypeEnum.ADMIN.getCode().equals(userInfo.getType())){
            // 管理员不需要进行条件判断
            return;
        }
        if(UserTypeEnum.PLAT.getCode().equals(userInfo.getType())){
            String sb = "plat_id=" +
                    userInfo.getPlatId();
            pageQuery.setDataAuth(sb);
        }else{
            String sb = "plat_id=" +
                    userInfo.getPlatId() +
                    " and " +
                    " agent_id = " +
                    userInfo.getAgentId();
            pageQuery.setDataAuth(sb);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveInvite(AgentInviteDto agentInviteDto) {
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        if(!UserTypeEnum.AGENT.getCode().equals(userInfo.getType())){
            throw new IllegalArgumentException(ErrorEnums.ROLES_NOT_OPT.name());
        }
        // 查询是否已经存在有效的邀请码
        int countStart = agentInviteMapper.countByStartTime(userInfo.getPlatId(), userInfo.getAgentId(), agentInviteDto.getStartTime() );
        int countEnd = agentInviteMapper.countByStartTime(userInfo.getPlatId(), userInfo.getAgentId(), agentInviteDto.getEndTime() );
        if(countStart+countEnd > 0){
            throw new IllegalArgumentException(ErrorEnums.TIME_RANGE_EXITS.name());
        }
        EdenPlatAgentInvite invite = new EdenPlatAgentInvite();
        invite.setAgentId(userInfo.getAgentId());
        invite.setPlatId(userInfo.getPlatId());
        invite.setInviteCode(InviteCodeGenerator.generateInviteCode());
        invite.setStatus(1);
        invite.setStartTime(agentInviteDto.getStartTime());
        invite.setEndTime(agentInviteDto.getEndTime());
        agentInviteMapper.insert(invite);
    }
    @Transactional(rollbackFor = Exception.class)
    public void cancelCode(Long id){
        UserInfoDto userInfo = WebUserUtils.getUserInfo();
        agentInviteMapper.updateCodeCancel(userInfo.getPlatId(), userInfo.getAgentId(), id);
    }
}
